<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Exception\XZXValidationException;
use App\Service\MchInfoService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Contract\TranslatorInterface;
use App\Constants\XZXResponseCode;

/**
 * Class MchInfoController
 * @package App\Controller
 *
 * @Controller(prefix="/admin/api/mchInfo")
 */
class MchInfoController extends AdminBaseController
{
    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var MchInfoService
     */
    protected $MchInfoService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale()
    {
        if($this->request->header('locale') == 'en')
        {
            $this->translator->setLocale('en');
        }
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            //不是超级管理员的，要判断要查看的商户id是否在他关联的商户里面
            $param['mchIdList'] =  $ext['mchIdList'];
            if(!empty($param['mchIdList']) && !in_array($param['id'],$param['mchIdList'])){
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        return $this->MchInfoService->get($param);
    }

    /**
     * 查看
     * @PostMapping(path = "getConfig")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getConfig(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchId' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
            // CustomUtils::xzxDebug("==================");
            // CustomUtils::xzxDebug($param['mchIdList']);
            if(!empty($param['mchIdList']) && !in_array($param['mchId'],$param['mchIdList'])){
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        return $this->MchInfoService->getConfig($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'                           => 'required|uuid',
                'url'                          => 'required',
                'email'                        => 'required|email',
                'mchName'                      => 'required',
                'mobile'                       => 'required|regex:/^1[3456789]\d{9}$/',
                'registerCertificateNo'        => 'required',
                'bankAccountName'              => 'required',
                'bankAccountNo'                => 'required',
                'bankOpenBankNo'               => 'required',
                'registerAddress'              => 'required',
                'corporation'                  => 'required',
                'phone'                        => 'required',
                'registerCert'                 => 'required',
                'companyPolice'                => 'required',
                'companyAgentPassport'         => 'required',
                'corporationCert'              => 'required',
                'corporationDecision'          => 'required',
                'nnc'                          => 'required',
                'registerAddressCert'          => 'required',
                'bankAccountNoCert'            => 'required',
                'legalPersonCert'              => 'required',
                'officeCert'                   => 'required',
                'fieldStatus'                  => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
            if(!empty($param['mchIdList']) && !in_array($param['id'],$param['mchIdList'])){
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        $param['createBy']  = $ext['createBy'];
        $param['source']    = 2;
        return $this->MchInfoService->edit($param);
    }

    /**
     * 设置配置
     * @PostMapping(path = "editConfig")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function editConfig(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchId'                => 'required|uuid',
                'mchName'              => 'required',
                'channelCollection'    => 'required|array',
                'settleRateId'         => 'required|uuid',
                'settleExchangeRateId' => 'required|uuid',
                'riskId'               => 'required|uuid',
                'settleCurrency'       => 'required',
                'transCurrency'        => 'required',
                'salesId'              => 'sometimes|uuid',
                'mchTagId'             => 'sometimes',
                'apiStatus'            => 'sometimes|integer|max:1|min:0',
                'regStatus'            => 'sometimes',
                'loginStatus'          => 'sometimes|integer|max:1|min:0',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
            if(!empty($param['mchIdList']) && !in_array($param['mchId'],$param['mchIdList'])){
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        $param['createBy']  = $ext['createBy'];
        $param['updateBy']  = $ext['updateBy'];
        CustomUtils::xzxDebug($param);
        return $this->MchInfoService->editConfig($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'email'                        => 'required|email',
                'url'                          => 'required',
                'mchName'                      => 'required',
                'mobile'                       => 'required|regex:/^1[3456789]\d{9}$/',
                'registerCertificateNo'        => 'required',
                'bankAccountName'              => 'required',
                'bankAccountNo'                => 'required',
                'bankOpenBankNo'               => 'required',
                'registerAddress'              => 'required',
                'corporation'                  => 'required',
                'phone'                        => 'required',
                'registerCert'                 => 'required',
                'companyPolice'                => 'required',
                'companyAgentPassport'         => 'required',
                'corporationCert'              => 'required',
                'corporationDecision'          => 'required',
                'nnc'                          => 'required',
                'registerAddressCert'          => 'required',
                'bankAccountNoCert'            => 'required',
                'legalPersonCert'              => 'required',
                'officeCert'                   => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['createBy']  = $ext['createBy'];
        $param['source']    = 2;
        return $this->MchInfoService->add($param);
    }

    /**
     * 审核
     * @PostMapping(path = "auth")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function auth(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'            => 'required|uuid',
                'regStatus'     => 'required|integer|max:3|min:1',
                // 'fieldStatus'   => 'array',

            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
            if(!empty($param['mchIdList']) && !in_array($param['id'],$param['mchIdList'])){
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        return $this->MchInfoService->auth($param);
    }

    /**
     * 注册成功后审核
     * @PostMapping(path = "reAuth")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function reAuth(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'            => 'required|uuid',
                'editStatus'    => 'required|integer|max:3|min:1',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
            if(!empty($param['mchIdList']) && !in_array($param['id'],$param['mchIdList'])){
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_PERMISSION_TO_OPERATE));
            }
        }
        return $this->MchInfoService->reAuth($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {
        $this->setlocale();

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page' => 'required|integer|min:1',
                'limit' => 'required|integer|min:1',
            ]
        );

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param                = $request->all();
        $ext                  = $this->request->getAttribute("ext");
        $param['isSuperRole'] = $ext['isSuperRole'];
        if (!$param['isSuperRole']) {
            $param['mchIdList'] = $ext['mchIdList'];
            // CustomUtils::xzxDebug("==================");
            // CustomUtils::xzxDebug($param['mchIdList']);
        }

        if(isset($param['search'])){

            $search = $param['search'];

            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'mchName');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            CustomUtils::xzxAddSearch($param, $search, 'tagIdList');

            if (empty($param['tagIdList'])) {
                unset($param['tagIdList']);
            }

            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }

        return $this->MchInfoService->list($param);
    }

    /**
     * 选项
     * @PostMapping(path = "option")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function option(RequestInterface $request) {
        $param = $request->all();
        return $this->MchInfoService->getOption($param);
    }

    /**
     * 变更日志
     * @PostMapping(path = "log")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function log(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->MchInfoService->log($param);
    }

    /**
     * 配置变更日志
     * @PostMapping(path = "channelMchConnLogList")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function channelMchConnLogList(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'mchNo' => 'required',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->MchInfoService->getChannelMchConnLogList($param);
    }
   
}
